import React, { Component } from "react";
import {Table, Button, Modal, Form, Input, message, DatePicker, Select, Col, Row, AutoComplete
} from "antd";
import {
    PushRecordSearchApi
} from "../js/api.js";
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;


class queryRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            // allCategory: [],
            // allStatus: []
            isSearch: false,
            classNameArr: [],
            existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            // searchText2: '',

            detailVisible: false,
            detailExist: false,

            searchChartLoading: true,
            chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let searchData = []
        let startTime = moment().format('YYYY-MM-DD')
        let endTime = moment().format('YYYY-MM-DD')
        PushRecordSearchApi(undefined, undefined, undefined, startTime, endTime, undefined)
            .then(res => {
            res.data.forEach((item, index) => {
                searchData.push({
                    key: index + 1,
                    name: item.name,
                    pushUserName: item.pushUserName,
                    pushTime: item.pushTime,
                    pushType: item.pushType,
                    pushStatus: item.pushStatus,
                });
                //statusData.push(item.statusString);
            });
            this.setState({
                isSearch: true,
                searchData: searchData,
                tableLoading: false,
                alertVisible: false,
            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    }


    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.name == undefined && values.pushUserName == undefined && values.deadline == undefined
                && values.pushType == undefined && values.pushStatus == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                let startTime = null;
                let endTime = null;
                if(values.deadline != undefined){
                    startTime = moment(values.deadline[0]).format('YYYY-MM-DD');
                    endTime = moment(values.deadline[1]).format('YYYY-MM-DD');
                }
                let searchData = [];
                PushRecordSearchApi(values.name, values.pushUserName, values.pushType, startTime, endTime, values.pushStatus)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            searchData.push({
                                key: index + 1,
                                name: item.name,
                                pushUserName: item.pushUserName,
                                pushTime: item.pushTime,
                                pushType: item.pushType,
                                pushStatus: item.pushStatus,
                            });
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }



    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "学校名称",
            dataIndex: "name",
            key: "name",
        },
        {
            title: "推送人",
            dataIndex: "pushUserName",
            key: "pushUserName",
        },
        {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime",
        },
        {
            title: "推送类型",
            dataIndex: "pushType",
            key: "pushType",
        },
        {
            title: "推送状态",
            dataIndex: "pushStatus",
            key: "pushStatus",
        },
        ];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let nameWidth = undefined;
        let pushUserNameWidth = undefined;
        let pushTimeWidth = undefined;
        let pushTypeWidth = undefined;
        let pushStatusWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            nameWidth = 150;
            pushUserNameWidth = 90;
            pushTimeWidth = 150;
            pushTypeWidth = 120;
            pushStatusWidth = 90;
        }

            const columnsSearch = [{
                title: "序号",
                dataIndex: "key",
                key: "key",
                width: keyWidth,
            }, {
                title: "学校名称",
                dataIndex: "name",
                key: "name",
                width: nameWidth,
            }, {
                title: "推送人",
                dataIndex: "pushUserName",
                key: "pushUserName",
                width: pushUserNameWidth
            }, {
                title: '推送时间',
                dataIndex: 'pushTime',
                key: 'pushTime',
                width: pushTimeWidth,
                sorter: (a, b) => new Date(a.pushTime).getTime() - new Date(b.pushTime).getTime(),
                sortOrder: sortedInfo2.columnKey === 'pushTime' && sortedInfo2.order,
            }, {
                title: '推送类型',
                dataIndex: 'pushType',
                key: 'pushType',
                width: pushTypeWidth,
            },
            {
                title: "推送状态",
                dataIndex: "pushStatus",
                key: "pushStatus",
                width: pushStatusWidth,
                render: (text) => {
                    if (text == '推送成功') { return (<span style={{ color: 'green' }}>推送成功</span>) }
                    else if (text == '推送失败') { return (<span style={{ color: 'red' }}>推送失败</span>) }
                }
            },
        ];



        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={11}>
                            <FormItem
                                label="学校名称"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("name", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.classNameArr}
                                        placeholder="请输入学校名称"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={11}>
                            <FormItem
                                label="推送人"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushUserName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入推送人"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="推送类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushType", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择推送类型">
                                        <Option value="日巡检报告">日巡检报告</Option>
                                        <Option value="周巡检报告">周巡检报告</Option>
                                        <Option value="月巡检报告">月巡检报告</Option>
                                        <Option value="隐患报告">隐患报告</Option>
                                        <Option value="巡更报告">巡更报告</Option>
                                        <Option value="考勤进出报告">考勤进出报告</Option>
                                        <Option value="考勤统计报告">考勤统计报告</Option>
                                        <Option value="事件报告">事件报告</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="推送状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushStatus", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择推送状态">
                                        <Option value={0}>推送成功</Option>
                                        <Option value={1}>推送失败</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div>
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange2}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                    </div>
                ) : (
                    <Table
                        dataSource={this.state.columnData}
                        columns={columns}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange}

                        expandedRowRender={(record) => {
                            return (
                                <InspectConditionInnerTable
                                    //wrappedComponentRef={(inst) => this.teammateTableFormRef = inst}
                                    //ref="teammateTableRefresh"
                                    onRef={this.onRef}
                                    teamId={record.teamId}
                                    that={this} />)
                        }}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.data.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                )}
                {
                    this.state.detailExist ? (
                        <InspectConditionDetail
                            visible={this.state.detailVisible}
                            currentInspectPlanIds={this.state.currentInspectPlanIds}
                            currentItems={this.state.currentItems}
                            currentStatusArr={this.state.currentStatusArr}
                            currentSinglePlanNormalArr={this.state.currentSinglePlanNormalArr}
                            that={this} />
                    ) : null
                }

                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'每日巡检完成情况展示图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
            </div>
        )
    }
}
const QueryRecord = Form.create()(queryRecord);

export { QueryRecord }